import * as THREE from "three";
import EventEmitter from "./EventEmitter";
import { TextureLoader } from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader";
import { FontLoader } from "three/examples/jsm/loaders/FontLoader";
import sources from "../sources";
export default class Resources extends EventEmitter {
  constructor() {
    super();
    this.sources = sources;

    this.items = {};
    this.toLoad = this.sources.length;
    this.loaded = 0;
    
    this.setLoaders();
    this.startLoading();
  }
  
  setLoaders() {
    this.loaders = {};

    this.loaders.gltfLoader = new GLTFLoader();
    this.loaders.textureLoader = new THREE.TextureLoader();
    this.loaders.cubeTextureLoader = new THREE.CubeTextureLoader();

    const dracoLoader = new DRACOLoader();
    dracoLoader.setDecoderPath("/static/gltf/");
    dracoLoader.setDecoderConfig({
      type: "js",
    });
    dracoLoader.preload();
    this.loaders.gltfLoader.setDRACOLoader(dracoLoader);

  }

  startLoading(){
    for(const source of this.sources){
        if(source.type === "gltfModel"){
            this.loaders.gltfLoader.load(source.path, (gltf) => {
                this.sourceLoaded(source,gltf);
            });
        }
        if(source.type === "texture"){
            this.loaders.textureLoader.load(source.path, (texture) => {
                this.sourceLoaded(source,texture);
            });
        }
    }
  }

  sourceLoaded(source,file){
    this.items[source.name] = file;
    this.loaded++;
    if(this.loaded === this.toLoad){//加载数量到了应该到达的数量
        this.trigger("ready");
    }
  }
}
